import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'

http.intercept.request = (config) => {
  console.log(config);
  const token = getApp().token
  if (token) {
    config.header = config.header || {}
    config.header.Authorization = token
  }
  return config
}

http.intercept.response = async (res) => {
  console.log(res);
  // 判断接口返回的状态码，如果是 401，代表 token 失效。
  if (res.statusCode === 401) {
    if (res.config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const currentPage = pageStack[pageStack.length - 1]
      wx.redirectTo({
        url: `/pages/login/index?returnUrl=/${currentPage.route}`
      })
      return res.data
    }
    // 调用刷新 token 接口，并以请求头的方式将 refreshToken 传递给后端
    const { code, data } = await wx.http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: getApp().refreshToken
      }
    })
    if (code !== 10000) return wx.utils.toast()
    getApp().setToken(data.token, data.refreshToken)
    const result = await wx.http({
      ...res.config
    })
    return result
  }
  // 解套
  // 剥离无用数据
  return res.data
}

wx.http = http

export default http